package com.demo.core.listener;


import com.demo.core.listener.event.ClearTableCacheEvent;
import com.demo.core.redis.RedisCache;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.transaction.event.TransactionPhase;
import org.springframework.transaction.event.TransactionalEventListener;

/**
 * @author Tan-Bowen
 * @description TODO 事务提交成功监听
 * @date 2021/7/27 16:21
 */
@Slf4j
@Component
public class TransactionalCommitClearTableCacheListener  {

    @Autowired
    private RedisCache redisCache;

    @TransactionalEventListener(fallbackExecution = true,phase= TransactionPhase.AFTER_COMMIT)
    public void handleClearTableCacheEvent(ClearTableCacheEvent clearTableCacheEvent){
        try{
            Boolean flag = redisCache.getJedis().delete(clearTableCacheEvent.getKey());
            log.info("删除缓存:[{}]条缓存",flag);
        }catch (Throwable e) {
            log.error("删除单表缓存出现异常:KEY:{},{}", clearTableCacheEvent.getKey(), e);
        }
    }
}
